<?php
/**
	* @Copyright   2008, XXXX-XXXX
	* All rights reserved. 
	* feature summary。
	* @filesource:	output_converter_json.php 
	* @author      	lipeng <lipengage@gmain.com> 
	* @package     	/ 
	* @version     	$Id: $ 
  */
/**
 * return json output converter
 */
class output_converter_json {

	function output_response(response_item $response_item) {
		$response = $response_item->get_response();
		if (!is_null($response)) {
			header('Content-Type: text/x-json;Charset=utf-8');
			echo json_encode($response);
			die();
		}
	}

	/**
	 * Generate a pretty-printed representation of a JSON object.
	 * 
	 * Taken from php comments for json_encode.
	 *
	 * @param string $json  JSON string
	 * @return string|false The pretty version, false if JSON was invalid
	 */
	static function json_format($json) {
		$tab = "  ";
		$new_json = "";
		$indent_level = 0;
		$in_string = false;
		$json_obj = json_decode($json);
		if (! $json_obj) {
			return false;
		}
		$json = json_encode($json_obj);
		$len = strlen($json);
		for ($c = 0; $c < $len; $c ++) {
			$char = $json[$c];
			switch ($char) {
				case '{':
				case '[':
					if (! $in_string) {
						$new_json .= $char . "\n" . str_repeat($tab, $indent_level + 1);
						$indent_level ++;
					} else {
						$new_json .= $char;
					}
					break;
				
				case '}':
				case ']':
					if (! $in_string) {
						$indent_level --;
						$new_json .= "\n" . str_repeat($tab, $indent_level) . $char;
					} else {
						$new_json .= $char;
					}
					break;
				
				case ',':
					if (! $in_string) {
						$new_json .= ",\n" . str_repeat($tab, $indent_level);
					} else {
						$new_json .= $char;
					}
					break;
				
				case ':':
					if (! $in_string) {
						$new_json .= ": ";
					} else {
						$new_json .= $char;
					}
					break;
				
				case '"':
					$in_string = ! $in_string;
				
				default:
					$new_json .= $char;
					break;
			}
		}
		return $new_json;
	}
}
